package www.dianbaozu.com.ui.my

import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentPersonalDetailsBinding
import www.dianbaozu.com.extension.save
import www.dianbaozu.com.ui.server.IMProxyActivity
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.CustomAreaEntity
import www.wen.com.common.lib.data.entities.GenderSelectionType
import www.wen.com.common.lib.data.entities.RequestBodyParameter
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.extension.glide.setImageUrl
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.MMKV_CITY
import www.wen.com.common.lib.helper.loading.KeyHelper.MMKV_PROVINCE
import www.wen.com.common.lib.helper.loading.KeyHelper.REFRESH_MY_KEY
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import www.wen.com.common.lib.util.DateUtil
import www.wen.com.common.lib.util.SpUtil
import www.wen.com.common.lib.util.StringUtil
import java.io.File


/**
 * @author WEN
 * @Description: 个人信息的页面
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class PersonalDetailsFragment : BaseLoadingFragment<FragmentPersonalDetailsBinding>() {

    private lateinit var imgFile: File

    private lateinit var mCustomAreaEntity: CustomAreaEntity

    private val mBaseApiViewModel: PersonalDetailsViewModel by viewModels()

    override val viewModel: BaseViewModel
        get() = mBaseApiViewModel

    override fun isEnableLoadingHelper(): Boolean = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter =
            TitleBarUniversalAdapter(requireActivity(), "个人信息", action = ::titleAction)

    override fun actionLeft() {
        //假如用户已经修改过而且没有保存则弹窗提醒
        if(mBaseApiViewModel.mEnableSave.get()!!){
            CreateXPopupHelper.createShowStandardAlertPopupView(PopupViewEntity().apply {
                context = requireActivity()
                standardAlertPopupViewTitle = "退出本次信息修改"
                isShow = true
                standardAlertPopupViewCancelContent = "取消"
                standardAlertPopupViewConfirmContent = "确认"
                standardAlertPopupViewContent = "你尚未保存修改,退出将不会保存本次修改."
                confirmFunction = {
                    if (requireActivity() is IMProxyActivity) {
                        finishMyself()
                    }else {
                        super.actionLeft()
                    }
                }
            })
        }else{
            if (requireActivity() is IMProxyActivity) {
                finishMyself()
            }else {
                super.actionLeft()
            }
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_personal_details

    override fun lazyInitView() {
        dataBinding.apply {
            viewModel = mBaseApiViewModel

            setImageUrl(ivProfileAvatar, SpUtil.decodeString(KeyHelper.MMKV_AVATAR)!!.imgUrl(), placeholder = R.drawable.user_default_icon,isCircle = true)
            tvInputNickname.text = SpUtil.decodeString(KeyHelper.MMKV_NICKNAME).apply {
                mBaseApiViewModel.mNickname = this!!
                mBaseApiViewModel.mOriginalNickname = this
            }
            tvInputSignature.text = SpUtil.decodeString(KeyHelper.MMKV_INTRO).apply {
                mBaseApiViewModel.mSignature = this!!
                mBaseApiViewModel.mOriginalSignature = this
            }

            tvGender.text = if (SpUtil.decodeInt(KeyHelper.MMKV_GENDER)!! == 1) "男" else if (SpUtil.decodeInt(KeyHelper.MMKV_GENDER)!! == 2) "女" else ""
            mBaseApiViewModel.mGender = SpUtil.decodeInt(KeyHelper.MMKV_GENDER, 0)!!
            mBaseApiViewModel.mOriginalGender = SpUtil.decodeInt(KeyHelper.MMKV_GENDER, 0)!!

            tvBirthday.text = SpUtil.decodeString(KeyHelper.MMKV_BIRTHDAY).apply {
                mBaseApiViewModel.mBirthday = this!!
                mBaseApiViewModel.mOriginalBirthday = this
            }
            val address = "${SpUtil.decodeString(MMKV_PROVINCE)}${SpUtil.decodeString(KeyHelper.MMKV_CITY)}"
            tvArea.text = address.apply {
                mBaseApiViewModel.mArea = this
                mBaseApiViewModel.mOriginalArea = this
            }
            tvMail.text = SpUtil.decodeString(KeyHelper.MMKV_EMAIL).apply {
                mBaseApiViewModel.mOriginalMail = this!!
                mBaseApiViewModel.mMail = this
            }
            if(SpUtil.decodeString(MMKV_PROVINCE)!!.isNotBlank()){
                mCustomAreaEntity =  CustomAreaEntity(SpUtil.decodeString(MMKV_PROVINCE)!!,SpUtil.decodeString(MMKV_CITY)!!)
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {

            override fun handleOnBackPressed() {
                if(mBaseApiViewModel.mEnableSave.get()!!){
                    actionLeft()
                }else{
                    findNavController().navigateUp()
                }
            }
        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.llAvatar -> selectAvatar()
            R.id.llNickname -> modifyNickname()
            R.id.llSignature -> modifySignature()
            R.id.llGender -> modifyGender()
            R.id.llBirthday -> modifyBirthday()
            R.id.llArea -> modifyArea()
            R.id.llMail -> modifyMail()
            R.id.tvSave -> saveInfo()
        }
    }

    private fun saveInfo() {
        val parts = mutableListOf<MultipartBody.Part>()
        if (this::imgFile.isInitialized) {
            parts.add(MultipartBody.Part.createFormData("files", imgFile.name, imgFile.asRequestBody("image/jpeg".toMediaTypeOrNull())))
        }
        mBaseApiViewModel.requestUpdateUserInfo(
                partMap = mapOf("userId" to SpUtil.decodeString(KeyHelper.MMKV_ID)!!.toRequestBody("text/plain".toMediaTypeOrNull())),
                body = RequestBodyParameter().apply {
                    birthday = dataBinding.tvBirthday.text.toString()
                    city = if (this@PersonalDetailsFragment::mCustomAreaEntity.isInitialized) mCustomAreaEntity.city else SpUtil.decodeString(MMKV_CITY)
                    email = dataBinding.tvMail.text.toString()
                    gender = mBaseApiViewModel.mGender
                    intro = dataBinding.tvInputSignature.text.toString()
                    nickName = dataBinding.tvInputNickname.text.toString()
                    province = if (this@PersonalDetailsFragment::mCustomAreaEntity.isInitialized) mCustomAreaEntity.province else SpUtil.decodeString(MMKV_PROVINCE)
                },
                *parts.toTypedArray()
        ) {
            it.originalNickName = mBaseApiViewModel.mOriginalNickname
            mBaseApiViewModel.mOriginalNickname = it.nickName
            mBaseApiViewModel.mOriginalSignature = it.intro
            mBaseApiViewModel.mOriginalGender = it.gender
            mBaseApiViewModel.mOriginalBirthday = it.birthday
            mBaseApiViewModel.mOriginalArea = "${it.province}${it.city}${it.platform}"
            mBaseApiViewModel.mOriginalMail = it.email
            mBaseApiViewModel.mOriginalHasImg = false

            mBaseApiViewModel.mNickname = it.nickName
            mBaseApiViewModel.mSignature = it.intro
            mBaseApiViewModel.mGender = it.gender
            mBaseApiViewModel.mBirthday = it.birthday
            mBaseApiViewModel.mArea = "${it.province}${it.city}${it.platform}"
            mBaseApiViewModel.mMail = it.email
            mBaseApiViewModel.mHasImg = false

            mBaseApiViewModel.mEnableSave.set(false)
            SpUtil.save(it)
            NIMHelper.updateIMInfo(it.nickName,it.avatar)

            postObject(REFRESH_MY_KEY,it)
            toast("更新成功")
        }
    }

    private fun modifyMail() {
        CreateXPopupHelper.createInputContextPopupView(PopupViewEntity().apply {
            isShow = true
            context = requireActivity()
            title = "邮箱地址"
            content = dataBinding.tvMail.text.toString()
            hintStr = "请输入邮箱地址"
            cancelContent = "取消"
            confirmContent = "确认"
            maxLength = 30
            resultCallBack = { view, result, popupView ->
                if (StringUtil.checkIsEmail(result) { toast(it) }) {
                    dataBinding.tvMail.text = result
                    mBaseApiViewModel.mMail = result
                    popupView.dismiss()
                }
            }
        })
    }

    private fun modifyArea() {
        if (mBaseApiViewModel.options1Items.isNullOrEmpty()) mBaseApiViewModel.requestArea()
        CreateXPopupHelper.createBottomAreaSelectPopupView(PopupViewEntity().apply {
            isShow = true
            context = requireActivity()
            if(this@PersonalDetailsFragment::mCustomAreaEntity.isInitialized){
                province = mCustomAreaEntity.province
                city = mCustomAreaEntity.city
            }
            options1Items = mBaseApiViewModel.options1Items
            options2Items = mBaseApiViewModel.options2Items
            options3Items = mBaseApiViewModel.options3Items
            resultCallBackArea = { view, result, popupView ->
                "${result.province}${result.city}${result.area}".also { dataBinding.tvArea.text = it }
                mCustomAreaEntity = result
                mBaseApiViewModel.mArea = dataBinding.tvArea.text.toString()
                popupView.dismiss()
            }
        })
    }

    private fun modifyGender() {
        CreateXPopupHelper.createGenderSelectionPopupView(PopupViewEntity().apply {
            isShow = true
            context = requireActivity()
            genderSelectionType = GenderSelectionType.pareGenderSelectionType(mBaseApiViewModel.mGender)
            resultGenderCallBack = { view, result, popupView ->
                dataBinding.tvGender.text = result.gender
                mBaseApiViewModel.mGender = result.ordinal
                popupView.dismiss()
            }
        })
    }

    private fun modifySignature() {
        CreateXPopupHelper.createInputContextPopupView(PopupViewEntity().apply {
            isShow = true
            context = requireActivity()
            content = dataBinding.tvInputSignature.text.toString()
            title = "个性签名"
            hintStr = "请输入个性签名"
            cancelContent = "取消"
            confirmContent = "确认"
            maxLength = 30
            resultCallBack = { view, result, popupView ->
                if (result.isBlank()) {
                    toast("个性签名不能为空")
                } else if(result.length>30){
                    toast("个性签名不能大于30个字符")
                }else {
                    dataBinding.tvInputSignature.text = result
                    mBaseApiViewModel.mSignature = result
                    popupView.dismiss()
                }
            }
        })
    }

    private fun modifyNickname() {
        CreateXPopupHelper.createInputContextPopupView(PopupViewEntity().apply {
            isShow = true
            context = requireActivity()
            content = dataBinding.tvInputNickname.text.toString()
            title = "修改昵称"
            hintStr = "请输入昵称"
            cancelContent = "取消"
            confirmContent = "确认"
            maxLength = 20
            resultCallBack = { view, result, popupView ->
                if (result.isBlank()) {
                    toast("昵称不能为空")
                }  else {
                    dataBinding.tvInputNickname.text = result
                    mBaseApiViewModel.mNickname = result
                    popupView.dismiss()
                }
            }
        })
    }

    private fun selectAvatar() {
        openPhotoAlbumAgency {
            val imgLocalFile = if(it[0].androidQToPath.isNullOrBlank()) File(it[0].compressPath) else File(it[0].androidQToPath)
            if (imgLocalFile.exists()) {
                imgFile = imgLocalFile
                setImageUrl(dataBinding.ivProfileAvatar, imgFile.absolutePath, placeholder = R.drawable.user_default_icon, isCircle = true)
                mBaseApiViewModel.mHasImg = true
            }
        }
    }

    private fun modifyBirthday() {
        CreateXPopupHelper.createBottomDateSelectPopupView(PopupViewEntity().apply {
            isShow = true
            context = requireActivity()
            timeStr = dataBinding.tvBirthday.text.toString()
            resultCallBackTime = { view, result, popupView ->
                dataBinding.tvBirthday.text = DateUtil.format(result, format = "yyyy-MM-dd")
                mBaseApiViewModel.mBirthday = DateUtil.format(result, format = "yyyy-MM-dd")
                popupView.dismiss()
            }
        })
    }

}



